<template>
  <div class="scroll-to-top">
    <i class="iconfont icon-fanhuidingbu" @click="scroll" v-show="show"></i>
  </div>
</template>

<script>
import { getScrolled, getViewportSize } from "../../tools";
import { onMounted, onUnmounted, ref } from "vue";
export default {
  name: "ScrollToTop",
  setup() {
    const show = ref(false);
    const scroll = () => {
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: "smooth",
      });
    };
    const setShow = () => {
      const scrolled = getScrolled().top;
      const height = getViewportSize().height;
      if (scrolled > height) {
        show.value = true;
      } else {
        show.value = false;
      }
    };
    onMounted(() => {
      document.addEventListener("scroll", setShow);
    });
    onUnmounted(() => {
      document.removeEventListener("scroll", setShow);
    });
    return {
      scroll,
      show,
    };
  },
};
</script>

<style scoped>
@font-face {
  font-family: "iconfont"; /* Project id 2698551 */
  src: url("//at.alicdn.com/t/font_2698551_6hwuttrh3x2.woff2?t=1627317434938")
      format("woff2"),
    url("//at.alicdn.com/t/font_2698551_6hwuttrh3x2.woff?t=1627317434938")
      format("woff"),
    url("//at.alicdn.com/t/font_2698551_6hwuttrh3x2.ttf?t=1627317434938")
      format("truetype");
}
.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
.icon-fanhuidingbu:before {
  content: "\e601";
}
.scroll-to-top i {
  font-size: 2rem;
  position: fixed;
  right: 2rem;
  bottom: 3rem;
  z-index: 900;
}
</style>